import 'dart:io';

import 'package:eyepetizer_example/config/string.dart';
import 'package:eyepetizer_example/utils/cache_image.dart';
import 'package:eyepetizer_example/widget/go_navigation.dart';
import 'package:eyepetizer_example/widget/loading_state_widget.dart';
import 'package:eyepetizer_example/widget/provider_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../model/common_item.dart';
import '../../model/video_detail_view_model.dart';
import '../../utils/cache_manager.dart';
import '../../utils/date_util.dart';
import '../../utils/history_repository.dart';
import '../../widget/video/video_item_widget.dart';
import '../../widget/video_play_widget.dart';

const VIDEO_SMALL_CARD_TYPE = 'videoSmallCard';

class VideoDetailPage extends StatefulWidget {

  Data videoData;

  VideoDetailPage(this.videoData, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailPageState();
  }
}

class _VideoDetailPageState extends State<VideoDetailPage> with WidgetsBindingObserver {

  late Data videoData;
  // 允许element在树周围移动(改变父节点), 而不会丢失状态
  GlobalKey<VideoPlayWidgetState> videoKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    videoData = widget.videoData;
    WidgetsBinding.instance.addObserver(this);
    CacheManager.preInit().then((cacheManager) => {
      HistoryRepository.saveWatchHistory(videoData)
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if(state == AppLifecycleState.paused) {
      videoKey.currentState?.pause();
    }else if(state == AppLifecycleState.resumed) {
      videoKey.currentState?.play();
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<VideoDetailViewModel>(
        model: VideoDetailViewModel(),
        onModelInit: (model)=> model.loadVideoData(videoData.id ?? 0),
        builder: (context, model, widget) {
          return _scaffold(model);
        });
  }

  Widget _statusBar() {
    return Container(
      height: MediaQuery.of(context).padding.top,
      color: Colors.black,
    );
  }

  Widget _scaffold(VideoDetailViewModel model) {
    return Scaffold(
      body: Column(
        children: [
          AnnotatedRegion(value: SystemUiOverlayStyle.light, child: _statusBar()),
          Hero(tag: '${videoData.id??0}${videoData.time}',
              child: VideoPlayWidget(
                playUrl: videoData.playUrl??"",
                key: videoKey,
              ),

          ),
          Expanded(
              flex: 1,
              child: LoadingStateWidget(
                viewState: model.viewState,
                retry: model.retry,
                child: Container(
                  decoration: _decoration(),
                  child: CustomScrollView(
                    slivers: [
                      _sliverToBoxAdapter(),
                      _sliverList(model),
                    ],
                  ),
                ),
              )
          )
        ],
      ),
    );
  }

  /// 页面背景
  Decoration _decoration() {
    return BoxDecoration(
      image: DecorationImage(
        fit: BoxFit.cover,
        image: cachedNetworkImageProvider(
          '${videoData.cover?.blurred}}/thumbnail/${MediaQuery.of(context).size.height}x${MediaQuery.of(context).size.width}'
        )
      )
    );
  }

  /// 视频下面的list头部展示
  Widget _sliverToBoxAdapter() {
    return SliverToBoxAdapter(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 视频标题
          _videoTitil(),
          // 视频分类及上架时间
          _videoTime(),
          // 视频描述
          _videoDescription(),
          // 视频的状态：点赞，转发，评论
          _videoState(),
          const Padding(padding: EdgeInsets.only(top: 10),
            child: Divider(
              height: 0.5,
              color: Colors.white,
            ),
          ),
          // 视频作者等介绍
          _videoAuthor(),
          const Divider(height: 0.5, color: Colors.white),
        ],
      ),
    );
  }

  /// 视频标题
  Widget _videoTitil() {
    return Padding(
      padding: const EdgeInsets.only(left: 10, top: 10),
      child: Text(
        videoData.title??"",
        style: const TextStyle(
          fontSize: 18,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
  /// 视频分类及上架时间
  Widget _videoTime() {
    return Padding(
      padding: const EdgeInsets.only(left: 10, top: 10),
      child: Text(
        '#${videoData.category} / ${formatDateMsByYMDHM(videoData.author?.latestReleaseTime??0)}',
        style: const TextStyle(color: Colors.white, fontSize: 12),
      ),
    );
  }
  /// 视频描述
  Widget _videoDescription() {
    return Padding(
      padding: const EdgeInsets.only(left: 10, top: 10, right: 10),
      child: Text(
        videoData.description??"",
        style: const TextStyle(color: Colors.white, fontSize: 14),
      ),
    );
  }
  /// 视频的状态：点赞，转发，评论
  Widget _videoState() {
    return Padding(padding: const EdgeInsets.only(left: 10, top: 10),
      child: Row(
        children: [
          _row('images/ic_like.png', '${videoData.consumption?.collectionCount ?? 0}'),
          Padding(
            padding: const EdgeInsets.only(left: 30),
            child: _row(
                'images/ic_share_white.png', '${videoData.consumption?.shareCount}'),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 30),
            child: _row(
                'images/icon_comment.png', '${videoData.consumption?.replyCount}'),
          ),
        ],
      ),
    );
  }
  Widget _row(String image, String text) {
    return Row(
      children: [
        Image.asset(
          image,
          height: 22,
          width: 22,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 3),
          child: Text(
            text,
            style: const TextStyle(color: Colors.white, fontSize: 13),
          ),
        )
      ],
    );
  }
  /// 视频作者等介绍
  Widget _videoAuthor() {
    return Row(
      children: [
        Padding(
          padding: const EdgeInsets.all(10),
          child: ClipOval(
            child: cacheImage(videoData.author?.icon??"", height: 40, width: 40),
          ),
        ),
        Expanded(
          flex: 1,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(videoData.author?.name??"",
                  style: const TextStyle(fontSize: 15, color: Colors.white)),
              Padding(
                padding: const EdgeInsets.only(top: 3),
                child: Text(
                  videoData.author?.description??"",
                  style: const TextStyle(fontSize: 13, color: Colors.white),
                ),
              )
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5)
            ),
            padding: const EdgeInsets.all(5),
            child: const Text(
              AppString.add_follow,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey,
                fontSize: 12
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _sliverList(VideoDetailViewModel model) {
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      if (model.itemList[index].type == VIDEO_SMALL_CARD_TYPE) {
        var data = model.itemList[index].data;
        if(data == null) {
          return Container();
        }
        return VideoItemWidget(
          data: data,
          callback: (){
            GoNavigator.back(context);
            GoNavigator.toPage(context, VideoDetailPage(
              data
            ));
          },
        );
      }
      return Padding(
        padding: const EdgeInsets.all(10),
        child: Text(
          model.itemList[index].data?.text ?? "",
          style: const TextStyle(
              color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16),
        ),
      );
    }, childCount: model.itemList.length));
  }
}
